home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / FAQs / netfaqs / C-abridged-faq < prev    next >
Text File  |  1994-08-01  |  40KB  |  1,268 lines

  1.  
  2. Newsgroups: comp.lang.c,comp.answers,news.answers
  3. From: scs@eskimo.com (Steve Summit)
  4. Subject: comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ)
  5. Date: 15 Apr 94 10:00:24 GMT
  6. Expires: Tue, 3 May 1994 00:00:00 GMT
  7. Followup-To: poster
  8. Organization: none, at the moment
  9. Lines: 1252
  10. Approved: news-answers-request@MIT.Edu
  11. Supersedes: <1994Apr01.0306.scs.0003@eskimo.com>
  12. X-Archive-Name: C-faq/abridged
  13. X-Last-Modified: March 1, 1994
  14. Xref: bloom-beacon.mit.edu comp.lang.c:38589 comp.answers:4922 news.answers:18103
  15.  
  16. Archive-name: C-faq/abridged
  17. Comp-lang-c-archive-name: C-FAQ-list.abridged
  18.  
  19. [Last modified March 1, 1994 by scs.]
  20.  
  21. This article contains minimal answers to the comp.lang.c frequently-
  22. asked questions list.  Please see the long version (posted on the
  23. first of each month, or see question 17.33 for availability) for more
  24. detailed explanations and references.
  25.  
  26.  
  27. Section 1. Null Pointers
  28.  
  29. 1.1:    What is this infamous null pointer, anyway?
  30.  
  31. A:    For each pointer type, there is a special value -- the "null
  32.     pointer" -- which is distinguishable from all other pointer
  33.     values and which is not the address of any object or function.
  34.  
  35. 1.2:    How do I "get" a null pointer in my programs?
  36.  
  37. A:    A constant 0 in a pointer context is converted into a null
  38.     pointer at compile time.  A "pointer context" is an
  39.     initialization, assignment, or comparison with one side a
  40.     variable or expression of pointer type, and (in ANSI standard C)
  41.     a function argument which has a prototype in scope declaring a
  42.     certain parameter as being of pointer type.  In other contexts
  43.     (function arguments without prototypes, or in the variable part
  44.     of variadic function calls) a constant 0 with an appropriate
  45.     explicit cast is required.
  46.  
  47. 1.3:    What is NULL and how is it #defined?
  48.  
  49. A:    NULL is simply a preprocessor macro, #defined as 0 (or
  50.     (void *)0), which is used (as a stylistic convention, in
  51.     preference to unadorned 0's) to generate null pointers,
  52.  
  53. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  54.     bit pattern as the internal representation of a null pointer?
  55.  
  56. A:    The same as any other machine: as 0 (or (void *)0).  (The
  57.     compiler makes the translation, upon seeing a 0, not the
  58.     preprocessor.)
  59.  
  60. 1.5:    If NULL were defined as "(char *)0," wouldn't that make function
  61.     calls which pass an uncast NULL work?
  62.  
  63. A:    Not in general.  The problem is that there are machines which
  64.     use different internal representations for pointers to different
  65.     types of data.  A cast is still required to tell the compiler
  66.     which kind of null pointer is required, since it may be
  67.     different from (char *)0.
  68.  
  69. 1.6:    I use the preprocessor macro "#define Nullptr(type) (type *)0"
  70.     to help me build null pointers of the correct type.
  71.  
  72. A:    This trick, though valid, does not buy much.
  73.  
  74. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  75.     null pointers valid?  What if the internal representation for
  76.     null pointers is nonzero?
  77.  
  78. A:    The construction "if(p)" works, regardless of the internal
  79.     representation of null pointers, because the compiler
  80.     essentially rewrites it as "if(p != 0)" and goes on to convert 0
  81.     into the correct null pointer.
  82.  
  83. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  84.  
  85. A:    Either; the distinction is entirely stylistic.
  86.  
  87. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  88.     the value of NULL changes, perhaps on a machine with nonzero
  89.     null pointers?
  90.  
  91. A:    No.  NULL is, and will always be, 0.
  92.  
  93. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  94.     is not?
  95.  
  96. A:    A "null pointer" is a language concept whose particular internal
  97.     value does not matter.  A null pointer is requested in source
  98.     code with the character "0".  "NULL" is a preprocessor macro,
  99.     which is always #defined as 0 (or (void *)0).
  100.  
  101. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  102.     do these questions come up so often?
  103.  
  104. A:    The fact that null pointers are represented both in source code,
  105.     and internally to most machines, as zero invites unwarranted
  106.     assumptions.  The use of a preprocessor macro (NULL) suggests
  107.     that the value might change later, or on some weird machine.
  108.  
  109. 1.12:    I'm still confused.  I just can't understand all this null
  110.     pointer stuff.
  111.  
  112. A:    A simple rule is, "Always use `0' or `NULL' for null pointers,
  113.     and always cast them when they are used as arguments in function
  114.     calls."
  115.  
  116. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  117.     be easier simply to require them to be represented internally by
  118.     zeroes?
  119.  
  120. A:    Such a requirement would accomplish little.
  121.  
  122. 1.14:    Seriously, have any actual machines really used nonzero null
  123.     pointers?
  124.  
  125. A:    Machines manufactured by Prime, Honeywell-Bull, and CDC, as well
  126.     as Symbolics Lisp Machines, have done so.
  127.  
  128. 1.15:    What does a run-time "null pointer assignment" error mean?
  129.  
  130. A:    It means that you've written through a null pointer.
  131.  
  132.  
  133. Section 2. Arrays and Pointers
  134.  
  135. 2.1:    I had the definition char a[6] in one source file, and in
  136.     another I declared extern char *a.  Why didn't it work?
  137.  
  138. A:    The declaration extern char *a simply does not match the actual
  139.     definition.  Use extern char a[].
  140.  
  141. 2.2:    But I heard that char a[] was identical to char *a.
  142.  
  143. A:    Not at all.  Arrays are not pointers.  A reference like x[3]
  144.     generates different code depending on whether x is an array or a
  145.     pointer.
  146.  
  147. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  148.     C?
  149.  
  150. A:    An lvalue of type array-of-T which appears in an expression
  151.     decays into a pointer to its first element; the type of the
  152.     resultant pointer is pointer-to-T.  So for an array a and
  153.     pointer p, you can say "p = a;" and then p[3] and a[3] will
  154.     access the same element.
  155.  
  156. 2.4:    Why are array and pointer declarations interchangeable as
  157.     function formal parameters?
  158.  
  159. A:    Since functions can never receive arrays as parameters, any
  160.     parameter declarations which "look like" arrays are treated by
  161.     the compiler as if they were pointers.
  162.  
  163. 2.5:    How can an array be an lvalue, if you can't assign to it?
  164.  
  165. A:    An array is not a "modifiable lvalue."
  166.  
  167. 2.6:    Why doesn't sizeof properly report the size of an array which is
  168.     a parameter to a function?
  169.  
  170. A:    The sizeof operator reports the size of the pointer parameter
  171.     which the function actually receives.
  172.  
  173. 2.7:    Someone explained to me that arrays were really just constant
  174.     pointers.
  175.  
  176. A:    An array name is "constant" in that it cannot be assigned to,
  177.     but an array is _not_ a pointer.
  178.  
  179. 2.8:    What is the real difference between arrays and pointers?
  180.  
  181. A:    Arrays automatically allocate space but are fixed (in size and
  182.     location); pointers are dynamic.
  183.  
  184. 2.9:    I came across some "joke" code containing the "expression"
  185.     5["abcdef"] .  How can this be legal C?
  186.  
  187. A:    Yes, array subscripting is commutative in C.  The array
  188.     subscripting operation a[e] is defined as being identical to
  189.     *((a)+(e)).
  190.  
  191. 2.10:    My compiler complained when I passed a two-dimensional array to
  192.     a routine expecting a pointer to a pointer.
  193.  
  194. A:    The rule by which arrays decay into pointers is not applied
  195.     recursively.  An array of arrays (i.e. a two-dimensional array
  196.     in C) decays into a pointer to an array, not a pointer to a
  197.     pointer.
  198.  
  199. 2.11:    How do I write functions which accept 2-dimensional arrays when
  200.     the "width" is not known at compile time?
  201.  
  202. A:    It's not particularly easy.
  203.  
  204. 2.12:    How do I declare a pointer to an array?
  205.  
  206. A:    Usually, you don't want to.  Consider using a pointer to one of
  207.     the array's elements instead.
  208.  
  209. 2.13:    What's the difference between array and &array?
  210.  
  211. A:    Under ANSI/ISO Standard C, &array yields a pointer to the entire
  212.     array.  An unadorned reference to an array yields a pointer to
  213.     the array's first element.
  214.  
  215. 2.14:    How can I dynamically allocate a multidimensional array?
  216.  
  217. A:    It is usually best to allocate an array of pointers, and then
  218.     initialize each pointer to a dynamically-allocated "row."  See
  219.     the full list for code samples.
  220.  
  221. 2.15:    How can I use statically- and dynamically-allocated
  222.     multidimensional arrays interchangeably when passing them to
  223.     functions?
  224.  
  225. A:    There is no single perfect method, but see the full list for
  226.     some ideas.
  227.  
  228. 2.16:    Can I simulate a non-0-based array with a pointer?
  229.  
  230. A:    Not if the pointer points outside of the block of memory it is
  231.     intended to access.
  232.  
  233. 2.17:    I passed a pointer to a function which initialized it, but the
  234.     pointer in the caller was unchanged.
  235.  
  236. A:    The called function probably altered only the passed copy of the
  237.     pointer.
  238.  
  239. 2.18:    I have a char * pointer that happens to point to some ints, and
  240.     I want to step it over them.  Why doesn't "((int *)p)++;" work?
  241.  
  242. A:    In C, a cast operator is a conversion operator, and by
  243.     definition it yields an rvalue, which cannot be assigned to, or
  244.     incremented with ++.
  245.  
  246. 2.19:    Can I use a void ** pointer to pass a generic pointer to a
  247.     function by reference?
  248.  
  249. A:    Not portably.
  250.  
  251.  
  252. Section 3. Memory Allocation
  253.  
  254. 3.1:    Why doesn't the code "char *answer; gets(answer);" work?
  255.  
  256. A:    The pointer variable "answer" has not been set to point to any
  257.     valid storage.  The simplest way to correct this fragment is to
  258.     use a local array, instead of a pointer.
  259.  
  260. 3.2:    I can't get strcat to work.  I tried "char *s1 = "Hello, ",
  261.     *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange
  262.     results.
  263.  
  264. A:    Again, the problem is that space for the concatenated result is
  265.     not properly allocated.
  266.  
  267. 3.3:    But the man page for strcat says that it takes two char *'s as
  268.     arguments.  How am I supposed to know to allocate things?
  269.  
  270. A:    In general, when using pointers you _always_ have to consider
  271.     memory allocation, at least to make sure that the compiler is
  272.     doing it for you.
  273.  
  274. 3.4:    I have a function that is supposed to return a string, but when
  275.     it returns to its caller, the returned string is garbage.
  276.  
  277. A:    Make sure that the memory to which the function returns a
  278.     pointer is correctly (i.e. not locally) allocated.
  279.  
  280. 3.5:    Why does some code carefully cast the values returned by malloc
  281.     to the pointer type being allocated?
  282.  
  283. A:    Before ANSI/ISO C, these casts were required to silence certain
  284.     warnings.
  285.  
  286. 3.6:    You can't use dynamically-allocated memory after you free it,
  287.     can you?
  288.  
  289. A:    No.  Some early documentation implied otherwise, but the claim
  290.     is no longer valid.
  291.  
  292. 3.7:    How does free() know how many bytes to free?
  293.  
  294. A:    The malloc/free package remembers the size of each block it
  295.     allocates and returns.
  296.  
  297. 3.8:    So can I query the malloc package to find out how big an
  298.     allocated block is?
  299.  
  300. A:    Not portably.
  301.  
  302. 3.9:    When I free a dynamically-allocated structure containing
  303.     pointers, do I have to free each subsidiary pointer first?
  304.  
  305. A:    Yes.
  306.  
  307. 3.10:    Why doesn't my program's memory usage go down when I free
  308.     memory?
  309.  
  310. A:    Most implementations of malloc/free do not return freed memory
  311.     to the operating system.
  312.  
  313. 3.11:    Must I free allocated memory before the program exits?
  314.  
  315. A:    You shouldn't have to.
  316.  
  317. 3.12:    Is it legal to pass a null pointer as the first argument to
  318.     realloc()?
  319.  
  320. A:    ANSI C sanctions this usage, but several earlier implementations
  321.     do not support it.
  322.  
  323. 3.13:    Is it safe to use calloc's zero-fill guarantee for pointer and
  324.     floating-point values?
  325.  
  326. A:    No.
  327.  
  328. 3.14:    What is alloca and why is its use discouraged?
  329.  
  330. A:    alloca allocates memory which is automatically freed when the
  331.     function which called alloca returns.  alloca cannot be written
  332.     portably, is difficult to implement on machines without a stack,
  333.     and fails under certain conditions if implemented simply.
  334.  
  335.  
  336. Section 4. Expressions
  337.  
  338. 4.1:    Why doesn't the code "a[i] = i++;" work?
  339.  
  340. A:    The variable i is both referenced and modified in the same
  341.     expression.
  342.  
  343. 4.2:    Under my compiler, the code "int i = 7;
  344.     printf("%d\n", i++ * i++);" prints 49.  Regardless of the order
  345.     of evaluation, shouldn't it print 56?
  346.  
  347. A:    The operations implied by the postincrement and postdecrement
  348.     operators ++ and -- are performed at some time after the
  349.     operand's former values are yielded and before the end of the
  350.     expression, but not necessarily immediately after, or before
  351.     other parts of the expression are evaluated.
  352.  
  353. 4.3:    How could the code "int i = 2; i = i++;" ever give 4?
  354.  
  355. A:    Undefined behavior means _anything_ can happen.
  356.  
  357. 4.4:    I just tried some allegedly-undefined code on an ANSI-conforming
  358.     compiler, and got the results I expected.
  359.  
  360. A:    A compiler may do anything it likes when faced with undefined
  361.     behavior, including doing what you expect.
  362.  
  363. 4.5:    Don't precedence and parentheses dictate order of evaluation?
  364.  
  365. A:    Operator precedence and explicit parentheses impose only a
  366.     partial ordering on the evaluation of an expression, which does
  367.     not generally include the order of side effects.
  368.  
  369. 4.6:    But what about the &&, ||, and comma operators?
  370.  
  371. A:    There is a special exception for those operators, (as well as
  372.     ?: ); left-to-right evaluation is guaranteed.
  373.  
  374. 4.7:    If I'm not using the value of the expression, should I use i++
  375.     or ++i to increment a variable?
  376.  
  377. A:    Since the two forms differ only in the value yielded, they are
  378.     entirely equivalent when only their side effect is needed.
  379.  
  380. 4.8:    Why doesn't the code "int a = 1000, b = 1000;
  381.     long int c = a * b;" work?
  382.  
  383. A:    You must manually cast one of the operands to (long).
  384.  
  385.  
  386. Section 5. ANSI C
  387.  
  388. 5.1:    What is the "ANSI C Standard?"
  389.  
  390. A:    In 1983, the American National Standards Institute (ANSI)
  391.     commissioned a committee to standardize the C language.  Their
  392.     work was ratified as ANS X3.159-1989, and has since been adopted
  393.     as ISO/IEC 9899:1990.
  394.  
  395. 5.2:    How can I get a copy of the Standard?
  396.  
  397. A:    ANSI X3.159 has been officially superseded by ISO 9899.  Copies
  398.     are available from ANSI in New York, or from Global Engineering
  399.     Documents in Irvine, CA.  See the unabridged list for addresses.
  400.  
  401. 5.3:    Does anyone have a tool for converting old-style C programs to
  402.     ANSI C, or for automatically generating prototypes?
  403.  
  404. A:    See the full list for details.
  405.  
  406. 5.4:    How do I keep the ANSI "stringizing" preprocessing operator from
  407.     stringizing the macro's name rather than its value?
  408.  
  409. A:    You must use a two-step #definition to force the macro to be
  410.     expanded as well as stringized.
  411.  
  412. 5.5:    Why can't I use const values in initializers and array
  413.     dimensions?
  414.  
  415. A:    The value of a const-qualified object is _not_ a constant
  416.     expression in the full sense of the term.
  417.  
  418. 5.6:    What's the difference between "char const *p" and
  419.     "char * const p"?
  420.  
  421. A:    The former is a pointer to a constant character; the latter is a
  422.     constant pointer to a character.
  423.  
  424. 5.7:    Why can't I pass a char ** to a function which expects a
  425.     const char **?
  426.  
  427. A:    The rule which permits slight mismatches in qualified pointer
  428.     assignments is not applied recursively.
  429.  
  430. 5.8:    My ANSI compiler complains about a mismatch when it sees
  431.  
  432.         extern int func(float);
  433.  
  434.         int func(x)
  435.         float x;
  436.         {...
  437.  
  438. A:    You have mixed the new-style prototype declaration
  439.     "extern int func(float);" with the old-style definition
  440.     "int func(x) float x;".  "Narrow" types are treated differently
  441.     according to which syntax is used.  This problem can be fixed by
  442.     avoiding narrow types, or by using either new-style (prototype)
  443.     or old-style syntax consistently.
  444.  
  445. 5.9:    Can you mix old-style and new-style function syntax?
  446.  
  447. A:    Doing so is currently perfectly legal.
  448.  
  449. 5.10:    Why does the declaration "extern f(struct x {int s;} *p);" give
  450.     me a warning message?
  451.  
  452. A:    A struct declared only within a prototype cannot be compatible
  453.     with other structs declared in the same source file.
  454.  
  455. 5.11:    I'm getting strange syntax errors inside code which I've
  456.     #ifdeffed out.
  457.  
  458. A:    Under ANSI C, #ifdeffed-out text must still consist of "valid
  459.     preprocessing tokens."  This means that there must be no
  460.     unterminated comments or quotes (i.e. no single apostrophes),
  461.     and no newlines inside quotes.
  462.  
  463. 5.12:    Can I declare main as void, to shut off these annoying "main
  464.     returns no value" messages?
  465.  
  466. A:    No.
  467.  
  468. 5.13:    Is exit(status) truly equivalent to returning status from main?
  469.  
  470. A:    Essentially.
  471.  
  472. 5.14:    Why does the ANSI Standard not guarantee more than six monocase
  473.     characters of external identifier significance?
  474.  
  475. A:    The problem is older linkers which cannot be forced (by mere
  476.     words in a Standard) to upgrade.
  477.  
  478. 5.15:    What is the difference between memcpy and memmove?
  479.  
  480. A:    memmove offers guaranteed behavior if the source and destination
  481.     arguments overlap.
  482.  
  483. 5.16:    My compiler is rejecting the simplest possible test programs,
  484.     with all kinds of syntax errors.
  485.  
  486. A:    Perhaps it is a pre-ANSI compiler.
  487.  
  488. 5.17:    Why are some ANSI/ISO Standard library routines showing up as
  489.     undefined, even though I've got an ANSI compiler?
  490.  
  491. A:    Perhaps you don't have ANSI-compatible headers and libraries.
  492.  
  493. 5.18:    Why won't frobozz-cc, which claims to be ANSI compliant, accept
  494.     this code?
  495.  
  496. A:    Are you sure that the code being rejected doesn't rely on some
  497.     non-Standard extension?
  498.  
  499. 5.19:    Why can't I perform arithmetic on a void * pointer?
  500.  
  501. A:    The compiler doesn't know the size of the pointed-to objects.
  502.  
  503. 5.20:    Is char a[3] = "abc"; legal?
  504.  
  505. A:    Yes, in ANSI C.
  506.  
  507. 5.21:    What are #pragmas and what are they good for?
  508.  
  509. A:    The #pragma directive provides a single, well-defined "escape
  510.     hatch" which can be used for extensions.
  511.  
  512. 5.22:    What does #pragma once mean?
  513.  
  514. A:    It is an extension implemented by some preprocessors to help
  515.     make header files idempotent.
  516.  
  517. 5.23:    What's the difference between implementation-defined,
  518.     unspecified, and undefined behavior?
  519.  
  520. A:    If you're writing portable code, ignore the distinctions.
  521.     Otherwise, see the full list.
  522.  
  523.  
  524. Section 6. C Preprocessor
  525.  
  526. 6.1:    How can I write a generic macro to swap two values?
  527.  
  528. A:    There is no good answer to this question.  The best all-around
  529.     solution is probably to forget about using a macro.
  530.  
  531. 6.2:    I have some old code that tries to construct identifiers with a
  532.     macro like "#define Paste(a, b) a/**/b ", but it doesn't work
  533.     any more.
  534.  
  535. A:    Try the ANSI token-pasting operator ##.
  536.  
  537. 6.3:    What's the best way to write a multi-statement cpp macro?
  538.  
  539. A:    #define Func() do {stmt1; stmt2; ... } while(0)  /* (no trailing ;) */
  540.  
  541. 6.4:    Is it acceptable for one header file to #include another?
  542.  
  543. A:    It's a question of style, and thus receives considerable debate.
  544.  
  545. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  546.  
  547. A:    No.
  548.  
  549. 6.6:    How can I use a preprocessor #if expression to detect
  550.     endianness?
  551.  
  552. A:    You probably can't.
  553.  
  554. 6.7:    I've got this tricky processing I want to do at compile time and
  555.     I can't figure out a way to get cpp to do it.
  556.  
  557. A:    Consider writing your own little special-purpose preprocessing
  558.     tool, instead.
  559.  
  560. 6.8:    How can I preprocess some code to remove selected conditional
  561.     compilations, without preprocessing everything?
  562.  
  563. A:    Look for a program called unifdef, rmifdef, or scpp.
  564.  
  565. 6.9:    How can I list all of the pre#defined identifiers?
  566.  
  567. A:    Try extracting printable strings from the compiler or
  568.     preprocessor executable.
  569.  
  570. 6.10:    How can I write a cpp macro which takes a variable number of
  571.     arguments?
  572.  
  573. A:    Here is one popular trick.  Note that the parentheses around
  574.     printf's argument list are in the macro call, not the
  575.     definition.
  576.  
  577.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  578.  
  579.         if(n != 0) DEBUG(("n is %d\n", n));
  580.  
  581.  
  582. Section 7. Variable-Length Argument Lists
  583.  
  584. 7.1:    How can I write a function that takes a variable number of
  585.     arguments?
  586.  
  587. A:    Use the <stdarg.h> (or older <varargs.h>) header.
  588.  
  589. 7.2:    How can I write a function that takes a format string and a
  590.     variable number of arguments, like printf, and passes them to
  591.     printf to do most of the work?
  592.  
  593. A:    Use vprintf, vfprintf, or vsprintf.
  594.  
  595. 7.3:    How can I discover how many arguments a function was actually
  596.     called with?
  597.  
  598. A:    Any function which takes a variable number of arguments must be
  599.     able to determine from the arguments themselves how many of them
  600.     there are.
  601.  
  602. 7.4:    I can't get the va_arg macro to pull in an argument of type
  603.     pointer-to-function.
  604.  
  605. A:    Use a typedef.
  606.  
  607. 7.5:    How can I write a function which takes a variable number of
  608.     arguments and passes them to some other function (which takes a
  609.     variable number of arguments)?
  610.  
  611. A:    In general, you cannot.
  612.  
  613. 7.6:    How can I call a function with an argument list built up at run
  614.     time?
  615.  
  616. A:    You can't.
  617.  
  618.  
  619. Section 8. Boolean Expressions and Variables
  620.  
  621. 8.1:    What is the right type to use for boolean values in C?  Why
  622.     isn't it a standard type?  Should #defines or enums be used for
  623.     the true and false values?
  624.  
  625. A:    C does not provide a standard boolean type, because picking one
  626.     involves a space/time tradeoff which is best decided by the
  627.     programmer.  The choice between #defines and enums is arbitrary
  628.     and not terribly interesting.
  629.  
  630. 8.2:    What if a built-in boolean or relational operator "returns"
  631.     something other than 1?
  632.  
  633. A:    When a boolean value is generated by a built-in operator, it is
  634.     guaranteed to be 1 or 0.  (This is _not_ true for some library
  635.     routines such as isalpha.)
  636.  
  637.  
  638. Section 9. Structs, Enums, and Unions
  639.  
  640. 9.1:    What is the difference between an enum and a series of
  641.     preprocessor #defines?
  642.  
  643. A:    At the present time, there is little difference.  The ANSI
  644.     standard states that enumerations are compatible with integral
  645.     types.
  646.  
  647. 9.2:    I heard that structures could be assigned to variables and
  648.     passed to and from functions, but K&R I says not.
  649.  
  650. A:    These operations are supported by all modern compilers.
  651.  
  652. 9.3:    How does struct passing and returning work?
  653.  
  654. A:    If you really need to know, see the unabridged list.
  655.  
  656. 9.4:    I have a program which works correctly, but dumps core after it
  657.     finishes.  Why?
  658.  
  659. A:    Check to see if a structure type declaration just before main is
  660.     missing its trailing semicolon, causing the compiler to believe
  661.     that main returns a structure.  See also question 17.21.
  662.  
  663. 9.5:    Why can't you compare structs?
  664.  
  665. A:    There is no reasonable way for a compiler to implement struct
  666.     comparison which is consistent with C's low-level flavor.
  667.  
  668. 9.6:    How can I read/write structs from/to data files?
  669.  
  670. A:    It is relatively straightforward to use fread and fwrite.
  671.  
  672. 9.7:    I came across some code that declared a structure with the last
  673.     member an array of one element, and then did some tricky
  674.     allocation to make the array act like it had several elements.
  675.     Is this legal and/or portable?
  676.  
  677. A:    An ANSI Interpretation Ruling has deemed it to be not strictly
  678.     conforming.
  679.  
  680. 9.8:    How can I determine the byte offset of a field within a
  681.     structure?
  682.  
  683. A:    ANSI C defines the offsetof macro, which should be used if
  684.     available.
  685.  
  686. 9.9:    How can I access structure fields by name at run time?
  687.  
  688. A:    Build a table of names and offsets, using the offsetof() macro.
  689.  
  690. 9.10:    Why does sizeof report a larger size than I expect for a
  691.     structure type, as if there was padding at the end?
  692.  
  693. A:    The alignment of arrays of structures must be preserved.
  694.  
  695. 9.11:    How can I turn off structure padding?
  696.  
  697. A:    There is no standard method.
  698.  
  699. 9.12:    Can I initialize unions?
  700.  
  701. A:    ANSI Standard C allows an initializer for the first member.
  702.  
  703. 9.13:    Can I pass constant values to routines which accept struct
  704.     arguments?
  705.  
  706. A:    No.  C has no way of generating anonymous struct values.
  707.  
  708.  
  709. Section 10. Declarations
  710.  
  711. 10.1:    How do you decide which integer type to use?
  712.  
  713. A:    If you might need large values, use long.  Otherwise, if space
  714.     is very important, use short.  Otherwise, use int.
  715.  
  716. 10.2:    What should the 64-bit type on new, 64-bit machines be?
  717.  
  718. A:    There are arguments in favor of long int and long long int,
  719.     among other options.
  720.  
  721. 10.3:    I can't seem to define a linked list node which contains a
  722.     pointer to itself.
  723.  
  724. A:    Structs in C can certainly contain pointers to themselves; the
  725.     discussion and example in section 6.5 of K&R make this clear.
  726.     Problems arise if an attempt is made to define (and use) a
  727.     typedef in the midst of such a declaration; avoid this.
  728.  
  729. 10.4:    How do I declare an array of N pointers to functions returning
  730.     pointers to functions returning pointers to characters?
  731.  
  732. A:    char *(*(*a[N])())();
  733.     Using a chain of typedefs, or the cdecl program, makes these
  734.     declarations easier.
  735.  
  736. 10.5:    How can I declare a function that returns a pointer to a
  737.     function of its own type?
  738.  
  739. A:    You can't do it directly.  Use a cast, or wrap a struct around
  740.     the pointer and return that.
  741.  
  742. 10.6:    My compiler is complaining about an invalid redeclaration of a
  743.     function, but I only define it once and call it once.
  744.  
  745. A:    Non-int functions must be declared before they are called.
  746.  
  747. 10.7:    What's the best way to declare and define global variables?
  748.  
  749. A:    It is best to place the definition in some central .c file, with
  750.     an external declaration in a header file.
  751.  
  752. 10.8:    What does extern mean in a function declaration?
  753.  
  754. A:    Nothing, really.
  755.  
  756. 10.9:    How do I initialize a pointer to a function?
  757.  
  758. A:    Use something like "extern int func(); int (*fp)() = func; " .
  759.  
  760. 10.10:    I've seen different methods used for calling through pointers to
  761.     functions.
  762.  
  763. A:    The extra parentheses and explicit * are now officially
  764.     optional, although some older implementations require them.
  765.  
  766. 10.11:    What's the auto keyword good for?
  767.  
  768. A:    Nothing.
  769.  
  770.  
  771. Section 11. Stdio
  772.  
  773. 11.1:    Why doesn't the code "char c; while((c = getchar()) != EOF)..."
  774.     work?
  775.  
  776. A:    The variable to hold getchar's return value must be an int.
  777.  
  778. 11.2:    Why doesn't the code scanf("%d", i); work?
  779.  
  780. A:    scanf needs pointers to the variables it is to fill in.
  781.  
  782. 11.3:    Why doesn't the code double d; scanf("%f", &d); work?
  783.  
  784. A:    Unlike printf, scanf uses %lf for double, and %f for float.
  785.  
  786. 11.4:    Why won't the code "while(!feof(infp)) {
  787.     fgets(buf, MAXLINE, infp); fputs(buf, outfp); }" work?
  788.  
  789. A:    EOF is only indicated _after_ an input routine has reached end-
  790.     of-file.
  791.  
  792. 11.5:    Why does everyone say not to use gets()?
  793.  
  794. A:    It cannot be prevented from overflowing the input buffer.
  795.  
  796. 11.6:    Why does errno contain ENOTTY after a call to printf?
  797.  
  798. A:    Don't worry about it.  It is only meaningful for a program to
  799.     inspect the contents of errno after an error has occurred.
  800.  
  801. 11.7:    My program's prompts and intermediate output don't always show
  802.     up on the screen, especially when I pipe the output through
  803.     another program.
  804.  
  805. A:    It is best to use an explicit fflush(stdout) whenever output
  806.     should definitely be visible.
  807.  
  808. 11.8:    When I read from the keyboard with scanf, it seems to hang until
  809.     I type one extra line of input.
  810.  
  811. A:    scanf was designed for free-format input, which is seldom what
  812.     you want when reading from the keyboard.
  813.  
  814. 11.9:    I'm trying to update a file in place, by using fopen mode "r+",
  815.     but it's not working.
  816.  
  817. A:    Be sure to call fseek between reading and writing.
  818.  
  819. 11.10:    How can I read one character at a time, without waiting for the
  820.     RETURN key?
  821.  
  822. A:    See question 16.1.
  823.  
  824. 11.11:    Will fflush(stdin) flush unread characters from the standard
  825.     input stream?
  826.  
  827. A:    No.
  828.  
  829. 11.12:    How can I redirect stdin or stdout from within a program?
  830.  
  831. A:    Use freopen.
  832.  
  833. 11.13:    Once I've used freopen, how can I get the original stdout back?
  834.  
  835. A:    It's not easy.  Try avoiding freopen.
  836.  
  837. 11.14:    How can I recover the file name given an open file descriptor?
  838.  
  839. A:    This problem is, in general, insoluble.  It is best to remember
  840.     the names of files yourself when you open them.
  841.  
  842.  
  843. Section 12. Library Subroutines
  844.  
  845. 12.1:    Why does strncpy not always write a '\0'?
  846.  
  847. A:    For mildly-interesting historical reasons.
  848.  
  849. 12.2:    I'm trying to sort an array of strings with qsort, using strcmp
  850.     as the comparison function, but it's not working.
  851.  
  852. A:    You'll have to write a "helper" comparison function which takes
  853.     two generic pointer arguments, converts them to char **, and
  854.     dereferences them, yielding char *'s which can be usefully
  855.     compared.
  856.  
  857. 12.3:    Now I'm trying to sort an array of structures with qsort.  My
  858.     comparison routine takes pointers to structures, but the
  859.     compiler complains that the function is of the wrong type for
  860.     qsort.  How can I cast the function pointer to shut off the
  861.     warning?
  862.  
  863. A:    The conversions must be in the comparison function, which must
  864.     be declared as accepting "generic pointers" (const void * or
  865.     char *).
  866.  
  867. 12.4:    How can I convert numbers to strings?
  868.  
  869. A:    Just use sprintf.
  870.  
  871. 12.5:    How can I get the time of day in a C program?
  872.  
  873. A:    Just use the time, ctime, and/or localtime functions.
  874.  
  875. 12.6:    How can I convert a struct tm or a string into a time_t?
  876.  
  877. A:    The ANSI mktime routine converts a struct tm to a time_t.  No
  878.     standard routine exists to parse strings.
  879.  
  880. 12.7:    How can I perform calendar manipulations?
  881.  
  882. A:    The ANSI/ISO Standard C mktime and difftime functions provide
  883.     support for both problems.
  884.  
  885. 12.8:    I need a random number generator.
  886.  
  887. A:    The standard C library has one: rand().
  888.  
  889. 12.9:    How can I get random integers in a certain range?
  890.  
  891. A:    One method is something like
  892.  
  893.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  894.  
  895. 12.10:    Each time I run my program, I get the same sequence of numbers
  896.     back from rand().
  897.  
  898. A:    You can call srand() to seed the pseudo-random number generator
  899.     with a more random initial value.
  900.  
  901. 12.11:    I need a random true/false value, so I'm taking rand() % 2, but
  902.     it's just alternating 0, 1, 0, 1, 0...
  903.  
  904. A:    Try using the higher-order bits.
  905.  
  906. 12.12:    I'm trying to port this old program.  Why do I get "undefined
  907.     external" errors for some library routines?
  908.  
  909. A:    Some semistandard routines have been renamed or replaced over
  910.     the years; see the full list for details.
  911.  
  912. 12.13:    I get errors due to library routines being undefined even though
  913.     I #include the right header files.
  914.  
  915. A:    You may have to explicitly ask for the correct libraries to be
  916.     searched.
  917.  
  918. 12.14:    I'm still getting errors due to library routines being
  919.     undefined, even though I'm requesting the right libraries.
  920.  
  921. A:    Library search order is significant; usually, you must search
  922.     the libraries last.
  923.  
  924. 12.15:    I need some code to do regular expression matching.
  925.  
  926. A:    regexp libraries abound; see the full list for details.
  927.  
  928. 12.16:    How can I split up a string into whitespace-separated arguments?
  929.  
  930. A:    Try strtok.
  931.  
  932.  
  933. Section 13. Lint
  934.  
  935. 13.1:    I just typed in this program, and it's acting strangely.  Can
  936.     you see anything wrong with it?
  937.  
  938. A:    Try running lint first.
  939.  
  940. 13.2:    How can I shut off the "warning: possible pointer alignment
  941.     problem" message lint gives me for each call to malloc?
  942.  
  943. A:    It may be easier simply to ignore the message, perhaps in an
  944.     automated way with grep -v.
  945.  
  946. 13.3:    Where can I get an ANSI-compatible lint?
  947.  
  948. A:    See the unabridged list for two commercial products.
  949.  
  950.  
  951. Section 14. Style
  952.  
  953. 14.1:    Is the code "if(!strcmp(s1, s2))" good style?
  954.  
  955. A:    Not particularly.
  956.  
  957. 14.2:    What's the best style for code layout in C?
  958.  
  959. A:    There is no one "best style," but see the full list for a few
  960.     suggestions.
  961.  
  962. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  963.     standards?
  964.  
  965. A:    See the unabridged list.
  966.  
  967.  
  968. Section 15. Floating Point
  969.  
  970. 15.1:    My floating-point calculations are acting strangely and giving
  971.     me different answers on different machines.
  972.  
  973. A:    First, make sure that you have #included <math.h>, and correctly
  974.     declared other functions returning double.  If the problem isn't
  975.     that simple, see the full list for a brief explanation, or any
  976.     good programming book for a better one.
  977.  
  978. 15.2:    I keep getting "undefined: _sin" compilation errors.
  979.  
  980. A:    Make sure you're linking with the correct math library.
  981.  
  982. 15.3:    Where is C's exponentiation operator?
  983.  
  984. A:    Try using the pow() function.
  985.  
  986. 15.4:    How do I round numbers?
  987.  
  988. A:    The simplest way is with code like (int)(x + 0.5) .
  989.  
  990. 15.5:    How do I test for IEEE NaN and other special values?
  991.  
  992. A:    There is not yet a portable way, but see the full list for
  993.     ideas.
  994.  
  995. 15.6:    I'm having trouble with a Turbo C program which crashes and says
  996.     something like "floating point formats not linked."
  997.  
  998. A:    Some compilers for small machines, including Turbo C, attempt to
  999.     leave out floating point support if it looks like it will not be
  1000.     needed.  The programmer must occasionally insert an extra,
  1001.     explicit call to a floating-point library routine to force
  1002.     loading of floating-point support.
  1003.  
  1004.  
  1005. Section 16. System Dependencies
  1006.  
  1007. 16.1:    How can I read a single character from the keyboard without
  1008.     waiting for a newline?
  1009.  
  1010. A:    Contrary to popular belief and many people's wishes, this is not
  1011.     a C-related question.  How to do so is a function of the
  1012.     operating system in use.
  1013.  
  1014. 16.2:    How can I find out if there are characters available for reading
  1015.     (and if so, how many)?  Alternatively, how can I do a read that
  1016.     will not block if there are no characters available?
  1017.  
  1018. A:    These, too, are entirely operating-system-specific.
  1019.  
  1020. 16.3:    How can I clear the screen?
  1021.  
  1022. A:    Such things depend on the output device you're using.
  1023.  
  1024. 16.4:    How do I read the mouse?
  1025.  
  1026. A:    What system are you using?
  1027.  
  1028. 16.5:    How can my program discover the complete pathname to the
  1029.     executable file from which it was invoked?
  1030.  
  1031. A:    argv[0] may contain all or part of the pathname.  You may be
  1032.     able to duplicate the command language interpreter's search path
  1033.     logic to locate the executable.
  1034.  
  1035. 16.6:    How can a process change an environment variable in its caller?
  1036.  
  1037. A:    In general, it cannot.
  1038.  
  1039. 16.7:    How can I check whether a file exists?
  1040.  
  1041. A:    You can try the access() routine.
  1042.  
  1043. 16.8:    How can I find out the size of a file, prior to reading it in?
  1044.  
  1045. A:    You might be able to get an estimate using stat() or
  1046.     fseek/ftell.
  1047.  
  1048. 16.9:    How can a file be shortened in-place without completely clearing
  1049.     or rewriting it?
  1050.  
  1051. A:    There are various ways to do this, but there is no truly
  1052.     portable solution.
  1053.  
  1054. 16.10:    How can I implement a delay, or time a user's response, with
  1055.     sub-second resolution?
  1056.  
  1057. A:    Unfortunately, there is no portable way.
  1058.  
  1059. 16.11:    How can I read in an object file and jump to routines in it?
  1060.  
  1061. A:    You want a dynamic linker and/or loader.
  1062.  
  1063. 16.12:    How can I invoke an operating system command from within a
  1064.     program?
  1065.  
  1066. A:    Use system().
  1067.  
  1068. 16.13:    How can I invoke an operating system command and trap its
  1069.     output?
  1070.  
  1071. A:    Unix and some other systems provide a popen() routine.
  1072.  
  1073. 16.14:    How can I read a directory in a C program?
  1074.  
  1075. A:    See if you can use the opendir() and readdir() routines.
  1076.  
  1077. 16.15:    How can I do serial ("comm") port I/O?
  1078.  
  1079. A:    It's system-dependent.
  1080.  
  1081.  
  1082. Section 17. Miscellaneous
  1083.  
  1084. 17.1:    What can I safely assume about the initial values of variables
  1085.     which are not explicitly initialized?
  1086.  
  1087. A:    Variables with "static" duration start out as 0, as if the
  1088.     programmer had initialized them.  Variables with "automatic"
  1089.     duration, and dynamically-allocated memory, start out containing
  1090.     garbage (with the exception of calloc).
  1091.  
  1092. 17.2:    What's wrong with
  1093.  
  1094.         f() { char a[] = "Hello, world!"; }
  1095.  
  1096. A:    Perhaps you have a pre-ANSI compiler.
  1097.  
  1098. 17.3:    How can I write data files which can be read on other machines
  1099.     with different data formats?
  1100.  
  1101. A:    The best solution is to use text files.
  1102.  
  1103. 17.4:    How can I delete a line from the middle of a file?
  1104.  
  1105. A:    Short of rewriting the file, you probably can't.
  1106.  
  1107. 17.5:    How can I return several values from a function?
  1108.  
  1109. A:    Either pass pointers to locations which the function can fill
  1110.     in, or have the function return a structure containing the
  1111.     desired values.
  1112.  
  1113. 17.6:    How can I call a function, given its name as a string?
  1114.  
  1115. A:    The most straightforward thing to do is maintain a
  1116.     correspondence table of names and function pointers.
  1117.  
  1118. 17.7:    I seem to be missing the system header file <sgtty.h>.  Can
  1119.     someone send me a copy?
  1120.  
  1121. A:    You cannot just pick up a copy of someone else's header file and
  1122.     expect it to work, since the definitions within header files are
  1123.     frequently system-dependent.  Contact your vendor.
  1124.  
  1125. 17.8:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  1126.     from C?
  1127.  
  1128. A:    The answer is entirely dependent on the machine and the specific
  1129.     calling sequences of the various compilers in use.
  1130.  
  1131. 17.9:    Does anyone know of a program for converting Pascal or FORTRAN
  1132.     to C?
  1133.  
  1134. A:    Several public-domain programs are available, namely ptoc, p2c,
  1135.     and f2c.  See the full list for details.
  1136.  
  1137. 17.10:    Can I use a C++ compiler to compile C code?
  1138.  
  1139. A:    Not necessarily; C++ is not a strict superset of C.
  1140.  
  1141. 17.11:    I'm looking for C development tools (cross-reference generators,
  1142.     code beautifiers, etc.).
  1143.  
  1144. A:    See the full list for a few names.
  1145.  
  1146. 17.12:    Where can I get copies of all these public-domain programs?
  1147.  
  1148. A:    See the regular postings in the comp.sources.unix and
  1149.     comp.sources.misc newsgroups for information.
  1150.  
  1151. 17.13:    When will the next Obfuscated C Code Contest be held?  How can I
  1152.     get a copy of the previous winning entries?
  1153.  
  1154. A:    See the full list, or send e-mail to judges@toad.com .
  1155.  
  1156. 17.14:    Why don't C comments nest?  Are they legal inside quoted
  1157.     strings?
  1158.  
  1159. A:    Nested comments would cause more harm than good.  The character
  1160.     sequences /* and */ are not special within double-quoted
  1161.     strings.
  1162.  
  1163. 17.15:    How can I get the ASCII value corresponding to a character?
  1164.  
  1165. A:    In C, if you have the character, you have its value.
  1166.  
  1167. 17.16:    How can I implement sets and/or arrays of bits?
  1168.  
  1169. A:    Use arrays of char or int, with a few macros to access the right
  1170.     bit at the right index.
  1171.  
  1172. 17.17:    What is the most efficient way to count the number of bits which
  1173.     are set in a value?
  1174.  
  1175. A:    This and many other similar bit-twiddling problems can often be
  1176.     sped up and streamlined using lookup tables.
  1177.  
  1178. 17.18:    How can I make this code more efficient?
  1179.  
  1180. A:    Efficiency is not important nearly as often as people tend to
  1181.     think it is.  Most of the time, by simply paying attention to
  1182.     good algorithm choices, perfectly acceptable results can be
  1183.     achieved.
  1184.  
  1185. 17.19:    Are pointers really faster than arrays?  How much do function
  1186.     calls slow things down?
  1187.  
  1188. A:    Precise answers to these and many similar questions depend of
  1189.     course on the processor and compiler in use.
  1190.  
  1191. 17.20:    Why does the code "char *p = "Hello, world!";
  1192.     p[0] = tolower(p[0]);" crash?
  1193.  
  1194. A:    String literals are not modifiable, except (in effect) when they
  1195.     are used as array initializers.
  1196.  
  1197. 17.21:    This program crashes before it even runs!
  1198.  
  1199. A:    Look for very large, local arrays.
  1200.     (See also question 9.4.)
  1201.  
  1202. 17.22:    What does "Segmentation violation" mean?
  1203.  
  1204. A:    It generally means that your program tried to access memory it
  1205.     shouldn't have.
  1206.  
  1207. 17.23:    My program is crashing, apparently somewhere down inside malloc.
  1208.  
  1209. A:    Make sure you aren't using more memory than you malloc'ed,
  1210.     especially for strings (which need strlen() + 1 bytes).
  1211.  
  1212. 17.24:    Does anyone have a C compiler test suite I can use?
  1213.  
  1214. A:    See the full list for several sources.
  1215.  
  1216. 17.25:    Where can I get a YACC grammar for C?
  1217.  
  1218. A:    See the ANSI Standard, or the unabridged list.
  1219.  
  1220. 17.26:    I need code to parse and evaluate expressions.
  1221.  
  1222. A:    Two available packages are mentioned in the full list.
  1223.  
  1224. 17.27:    I need to compare two strings for close, but not necessarily
  1225.     exact, equality.
  1226.  
  1227. A:    The traditional routine for doing this sort of thing involves
  1228.     the "soundex" algorithm.
  1229.  
  1230. 17.28:    How can I find the day of the week given the date?
  1231.  
  1232. A:    Use Zeller's congruence.
  1233.  
  1234. 17.29:    Will 2000 be a leap year?
  1235.  
  1236. A:    Yes.
  1237.  
  1238. 17.30:    How do you pronounce "char"?
  1239.  
  1240. A:    Like the English words "char," "care," or "car" (your choice).
  1241.  
  1242. 17.31:    What's a good book for learning C?
  1243.  
  1244. A:    There are far too many to list here; the full list contains a
  1245.     few pointers.
  1246.  
  1247. 17.32:    Are there any C tutorials on the net?
  1248.  
  1249. A:    There are at least two of them.
  1250.  
  1251. 17.33:    Where can I get extra copies of this list?
  1252.  
  1253. A:    For now, just pull it off the net; the unabridged version is
  1254.     normally posted on the first of each month, with an Expires:
  1255.     line which should keep it around all month.  It can also be
  1256.     found in the newsgroups comp.answers and news.answers .  Several
  1257.     sites archive news.answers postings and other FAQ lists,
  1258.     including this one: two sites are rtfm.mit.edu (directory
  1259.     pub/usenet), and ftp.uu.net (directory usenet).  The archie
  1260.     server should help you find others.
  1261.  
  1262.                     Steve Summit
  1263.                     scs@eskimo.com
  1264.  
  1265. This article is Copyright 1988, 1990-1994 by Steve Summit.
  1266. It may be freely redistributed so long as the author's name, and this
  1267. notice, are retained.
  1268.